package com.starhub.domain.annotate.client;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.starhub.application.collection.entity.KnowledgeCollection;
import com.starhub.application.collection.service.KnowledgeCollectionService;
import com.starhub.domain.annotate.annotation.DataFormatAnno;
import com.starhub.domain.annotate.enums.FormatDataEnums;
import com.starhub.domain.annotate.util.DataUtil;
import com.starhub.utils.Util;

import lombok.extern.slf4j.Slf4j;

/**
 * 单数据客户端
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-19
 */
@Slf4j
@Component
@DataFormatAnno(FormatDataEnums.SINGLEDATA)
public class SingleDataClient implements DataFormatClient{

    @Autowired
    private DataUtil dataUtil;

    @Autowired
    protected KnowledgeCollectionService knowledgeCollectionService;
    
    /**
     * 格式化数据
     * @param metaId 元数据表ID
     * @param data 数据
     * @return 格式化后的数据
     */
    @Override
    public List<String> formatData(String metaId, String data) {
        if (data == null || data.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        try {
            // 使用Gson解析JSON数组

            String jsonData = data.replace("```json", "").replace("```", "").trim();
            com.google.gson.Gson gson = new com.google.gson.Gson();
            String[] array = gson.fromJson(jsonData, String[].class);
            
            // 获取元数据集合信息
            KnowledgeCollection metaCollection = knowledgeCollectionService.selectById(Util.getLongValue(metaId));
            if (metaCollection == null) {
                throw new RuntimeException("元数据表不存在: " + metaId);
            }
            
            // 使用基类的通用业务逻辑处理数据
            return dataUtil.processDataItems(Arrays.asList(array), metaCollection);
            
        } catch (Exception e) {
            log.error("数据格式化失败: {}", data, e);
            throw new RuntimeException("数据格式化失败: " + data, e);
        }
    }

    @Override
    public List<String> getRealData(String metaId) {
        return new ArrayList<>();
    }
}
